package com.chinamobile.iot;


import com.chinamobile.iot.mqtt.interception.MessageHandler;
import com.chinamobile.iot.mqtt.server.Server;
import com.chinamobile.iot.mqtt.spi.impl.ProtocolProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

/**
 * Created by szl on 2017/3/29.
 * 在进程异常终止时，Spring框架会发送ContextClosedEvent，通过本Event可以做收尾处理，把内存中的数据保存到mongo中
 */
@Component
public class ShutdownListener implements ApplicationListener<ContextClosedEvent> {

    private static Logger logger = LoggerFactory.getLogger(ShutdownListener.class);
    @Autowired
    private ProtocolProcessor protocolProcessor;
    @Autowired(required = false)
    @Qualifier("extendMessageHandler")
    private MessageHandler messageHandler;
    @Autowired
    private Server server;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        logger.info("ShutdownListener::onApplicationEvent() is called");

        server.stopServer();
        // 断开所有连接
        protocolProcessor.disconnectAllClient();
        // 断开所有subscription
        if (messageHandler != null) {
            messageHandler.destroy();
        }
    }
}


